/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved.
 */
/**
 * 将字符串格式为yyyy-MM-dd的字符串转换成日期
 * @param fDate
 * @returns {Date}
 */
function strToDate(fDate) {
    var fullDate = fDate.split("-");
    return new Date(fullDate[0], fullDate[1] - 1, fullDate[2], 0, 0, 0);
}

//检查时间是否符合粒度，比如粒度是小时的话，时间范围只能是一天之内
function checkDate(startDateStr, endDateStr, lidu) {
    var resultObj = {'isSuccess': true, 'msg': ''};
    var startDate = strToDate(startDateStr);
    var endDate = strToDate(endDateStr);
    var intervalTime = endDate.getTime() - startDate.getTime();
    var days = Math.floor(intervalTime / (24 * 3600 * 1000));
    if (lidu == '3') {
        if (days > 31) {
            resultObj.isSuccess = false;
            resultObj.msg = Dolphin.i18n.get("passenger.noWiderThanOneMonth");
        }
    } else if (lidu == '4') {
        if (days > 182) {
            resultObj.isSuccess = false;
            resultObj.msg = Dolphin.i18n.get("passenger.noWiderThanMonths");
        }
    } else if (lidu == '5') {
        if (days > 365) {
            resultObj.isSuccess = false;
            resultObj.msg = Dolphin.i18n.get("passenger.noWiderThanOneYear");
        }
    } else {
        if (days > 1) {
            resultObj.isSuccess = false;
            resultObj.msg = Dolphin.i18n.get("passenger.noWiderThanOneDay");
        }
    }

    return resultObj;
}

$(function () {
    org.breezee.page = {
        const_vars: {
            bar_chartOption_legend_data: [],
            bar_chartOption_yAxis_data: [],
            bar_chartOption_series: [],
            line_chartOption_legend_data: [],
            line_chartOption_xAxis_data: [],
            line_chartOption_series: [],
            chartDiv: 'showDataDiv',
            shopCnt: 0,
            chartWidth: 0
        },

        init: function () {
            var loginCustomerId = $("#_loginCustomerId").val();
            var loginAccountId = $("#_loginAccountId").val();
            var loginVendorId = $("#_loginVendorId").val();

            if ((loginCustomerId != null && loginCustomerId != "")
                || (loginVendorId != null && loginVendorId != "")) {
                /*var optionUrl="/api/c666378c5d3b417d8e150c456a489d23@accountId="+loginAccountId;
                var ajaxType="get"
                var optionParam='{"properties":{}}'
                $("#customer_select").attr("optionUrl",optionUrl)
                    .attr("ajaxType",ajaxType)
                    .attr("optionParam", optionParam);*/

                let _this = $("#customer_select");
                Dolphin.ajax({
                    url: '/api/c666378c5d3b417d8e150c456a489d23@accountId=' + loginAccountId,
                    type: Dolphin.requestMethod.GET,
                    async: false,
                    onSuccess: function (reData) {
                        _this.append(
                            '<option value="">--' + Dolphin.i18n.get("account.pleaseSelect") + '--</option>');
                        $.each(reData.rows, function (index, obj) {
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });
                    }
                });
                $("#customer_select").select2();

            } else {
                /*var optionUrl="/api/742445c653654caaa4a1fa69eb651a9a"
                var ajaxType="post"
                var optionParam = '{"properties":{"category":"1"}}';
                $("#customer_select").attr("optionUrl",optionUrl)
                    .attr("ajaxType",ajaxType)
                    .attr("optionParam", optionParam);*/
                let _this = $("#customer_select");
                Dolphin.ajax({
                    url: '/api/742445c653654caaa4a1fa69eb651a9a',
                    type: Dolphin.requestMethod.POST,
                    async: false,
                    data: Dolphin.json2string({properties: {"category": "1"}}),
                    onSuccess: function (reData) {
                        _this.append(
                            '<option value="">--' + Dolphin.i18n.get("account.pleaseSelect") + '--</option>');
                        $.each(reData.rows, function (index, obj) {
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });
                    }
                });
                $("#customer_select").select2();
            }

            Dolphin.form.parse();
            this._dataList = this.dataList('#dataList');
            this._dataList.__columns[4].formatter = function (val) {
                return val.substr(0, 10);
            }
            this._dataTotalList = this.dataTotalList('#dataTotalList');
            this._dataTotalList.__columns[4].formatter = function (val) {
                return val;
            }
            this.initEvent();
            var shopCondition = {"selectCustomerId": loginCustomerId};
            if (loginCustomerId != null && loginCustomerId != "") {
                var _this = $("#shop_select");
                Dolphin.ajax({
                    url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                    type: Dolphin.requestMethod.POST,
                    async: false,
                    data: Dolphin.json2string({properties: shopCondition}),
                    onSuccess: function (reData) {
                        _this.append(
                            '<option value="">--' + Dolphin.i18n.get("account.pleaseSelect") + '--</option>');
                        $.each(reData.rows, function (index, obj) {
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });
                    }
                });
            }
            $(".js-example-basic-multiple").select2();
        },
        /**
         * 初始化页面事件
         */
        initEvent: function () {
            let me = this;
            /**
             * 绑定回车事件，触发搜索
             */
            $(document).keypress(function (e) {
                var eCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
                if (eCode == 13) {
                    $(".btn-query").click();
                }
            });

            //以柱状图展现
            $('.showBar').click(function () {
                console.log('... enter showBar ...');
                console.log(me.const_vars);
                dolphinEcharts.bar_chart(me.const_vars.bar_chartOption_legend_data,
                    me.const_vars.bar_chartOption_yAxis_data,
                    me.const_vars.bar_chartOption_series,
                    me.const_vars.chartDiv,
                    me.const_vars.shopCnt,
                    me.const_vars.chartWidth);

            });
            //以折线图展现
            $('.showLine').click(function () {
                console.log('... enter showLine ...');
                console.log(me.const_vars);
                dolphinEcharts.line_chart(me.const_vars.line_chartOption_legend_data,
                    me.const_vars.line_chartOption_xAxis_data,
                    me.const_vars.line_chartOption_series,
                    me.const_vars.chartDiv);
            });

            //选择客户
            $("#customer_select").change(function () {

                $("#shop_select").empty();

                var queryConditionObj = {};
                queryConditionObj.selectCustomerId = $(this).val();
                if ($("#followedFlag").is(':checked')) {
                    queryConditionObj.followed = 'Y';
                }
                queryConditionObj.selectShopType = $("#shopType").val();

                var _this = $("#shop_select");

                Dolphin.ajax({
                    url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                    type: Dolphin.requestMethod.POST,
                    async: false,
                    data: Dolphin.json2string({properties: queryConditionObj}),
                    onSuccess: function (reData) {

                        _this.append(
                            '<option value="">--' + Dolphin.i18n.get("account.pleaseSelect") + '--</option>');
                        $.each(reData.rows, function (index, obj) {
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });
                    }
                });

            });

            //选择门店类型
            $("#shopType").change(function () {

                $("#shop_select").empty();

                var queryConditionObj = {};
                queryConditionObj.selectCustomerId = $("#customer_select").val() || $("#_loginCustomerId").val();
                if ($("#followedFlag").is(':checked')) {
                    queryConditionObj.followed = 'Y';
                }
                queryConditionObj.selectShopType = $(this).val();

                var _this = $("#shop_select");

                Dolphin.ajax({
                    url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                    type: Dolphin.requestMethod.POST,
                    async: false,
                    data: Dolphin.json2string({properties: queryConditionObj}),
                    onSuccess: function (reData) {
                        _this.append(
                            '<option value="">--' + Dolphin.i18n.get("account.pleaseSelect") + '--</option>');
                        $.each(reData.rows, function (index, obj) {
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');

                        });
                    }
                });

            });

            //选择店铺
            $("#shop_select").change(function () {
                var selectedShopVal = $(this).val();
                if (selectedShopVal != null && selectedShopVal != "") {
                    var condition = '{"properties":{"customer_id_obj_ae": "' + selectedShopVal + '"}}';
                    $("#device_select").empty().attr("optionUrl", "/api/b6a1808e4fcd4844836eb802249ac30c").attr("optionParam", condition);
                    Dolphin.form.parseSelect($(".query-form").find('#device_select'));
                } else {
                    $("#device_select").empty()
                }

            })


            //默认门店，切换汇总方式
            $(".custom-radio").change(function () {

                me._dataList = me.dataList('#dataList');
                me._dataTotalList = me.dataTotalList('#dataTotalList');
                var shopType = $(this).val();
                var liduVal = $('#lidu_input');

                if (liduVal == '3') {
                    $(".lidu_hour").hide();
                    $(".lidu_day").show();
                    $(".lidu_week").hide();
                    $(".lidu_month").hide();
                    $("#btn_pressed_week").click();
                    if ('shop' == shopType) {
                        me._dataList.__columns[4].formatter = function (val) {
                            return val.substr(0, 10);
                        }
                        me._dataTotalList.__columns[4].formatter = function (val) {
                            return val;
                        }
                    } else {
                        me._dataList.__columns[6].formatter = function (val) {
                            return val.substr(0, 10);
                        }
                        me._dataTotalList.__columns[6].formatter = function (val) {
                            return val;
                        }
                    }


                } else if (liduVal == '4') {
                    $(".lidu_hour").hide();
                    $(".lidu_day").hide();
                    $(".lidu_week").show();
                    $(".lidu_month").hide();
                    $("#btn_pressed_month").click();
                    if ('shop' == shopType) {
                        me._dataList.__columns[4].formatter = function (val) {
                            var year = $("#startDate").val().substr(0, 4);
                            return getXDate(year, val) + ' 第' + val + '周';
                        }
                        me._dataTotalList.__columns[4].formatter = function (val) {
                            return val;
                        }
                    } else {
                        me._dataList.__columns[6].formatter = function (val) {
                            var year = $("#startDate").val().substr(0, 4);
                            return getXDate(year, val) + ' 第' + val + '周';
                        }
                        me._dataTotalList.__columns[6].formatter = function (val) {
                            return val;
                        }
                    }


                } else if (liduVal == '5') {
                    $(".lidu_hour").hide();
                    $(".lidu_day").hide();
                    $(".lidu_week").hide();
                    $(".lidu_month").show();
                    $("#btn_pressed_year").click();
                    if ('shop' == shopType) {
                        me._dataList.__columns[4].formatter = function (val) {
                            return val.substr(0, 7);
                        }
                        me._dataTotalList.__columns[4].formatter = function (val) {
                            return val;
                        }
                    } else {
                        me._dataList.__columns[6].formatter = function (val) {
                            return val.substr(0, 7);
                        }
                        me._dataTotalList.__columns[6].formatter = function (val) {
                            return val;
                        }
                    }

                } else {
                    $(".lidu_hour").show();
                    $(".lidu_day").hide();
                    $(".lidu_week").hide();
                    $(".lidu_month").hide();
                    $("#btn_pressed_day").click();
                    if ('shop' == shopType) {
                        me._dataList.__columns[4].formatter = function (val) {
                            var day = val.substr(0, 10);
                            var startHour = val.substr(11, 2);
                            var endHour = parseInt(startHour) + 1
                            return day + ' ' + startHour + ':00-' + endHour + ':00';
                        }
                        me._dataTotalList.__columns[4].formatter = function (val) {
                            return val;
                        }
                    } else {
                        me._dataList.__columns[6].formatter = function (val) {
                            var day = val.substr(0, 10);
                            var startHour = val.substr(11, 2);
                            var endHour = parseInt(startHour) + 1
                            return day + ' ' + startHour + ':00-' + endHour + ':00';
                        }
                        me._dataTotalList.__columns[6].formatter = function (val) {
                            return val;
                        }
                    }

                }

                if ("shop" == shopType) {
                    $(".device_div").hide();
                } else {
                    $(".device_div").show();
                }
            });

            //导出
            $(".btn-export").click(function () {


                if ($('input[name="_radio"]:checked').val() == "shop") {
                    var url = (org.breezee.context.contextPath == '/' ? '' : org.breezee.context.contextPath)
                        + '/api/fe1222f770a54abca1a4643345d5ed11';
                    var form = $("<form />");

                    form.attr({"style": "display: none", "target": '_blank', "method": "post", "action": url});
                    $('body').append(form);
                    var titleObj = {};
                    $.each(me._dataList.__columns, function (index, obj) {
                        titleObj[obj.code] = obj.title;
                    });
                    var value = Dolphin.json2string(titleObj);
                    var input = $("<input>");
                    input.attr({"name": "data[0]", "value": value, "type": "hidden"});
                    form.append(input);

                    $.each(me._dataList.data.rows, function (index, obj) {
                        var value = Dolphin.json2string(obj);
                        var input = $("<input>");
                        input.attr({"name": "data[" + (++index) + "]", "value": value, "type": "hidden"});
                        form.append(input);
                    });

                    var input = $("<input>");
                    input.attr({
                        "name": "excelName",
                        "value": Dolphin.i18n.get("passenger.storeEntryData") + Dolphin.date2string(new Date(), 'yyyyMMddhhmmss'),
                        "type": "hidden"
                    });
                    form.append(input);
                    form.submit();
                    form.remove();
                } else {
                    var queryConditionObj = Dolphin.form.getValue('.query-form');

                    me._dataList.opts.queryParams._loginTopCustomer = queryConditionObj._loginTopCustomer;

                    me._dataList.opts.queryParams._shopIdsStr = "";

                    if (queryConditionObj.customer_id_obj_ae != null && queryConditionObj.customer_id_obj_ae.length > 1) {
                        for (var i = 0; i < queryConditionObj.customer_id_obj_ae.length; i++) {
                            me._dataList.opts.queryParams._shopIdsStr += queryConditionObj.customer_id_obj_ae[i] + "|";
                        }
                        me._dataList.opts.queryParams._shopIdsStr = me._dataList.opts.queryParams._shopIdsStr.substring(0, me._dataList.opts.queryParams._shopIdsStr.length - 1);
                        queryConditionObj.customer_id_obj_ae = null;
                    } else if (queryConditionObj.customer_id_obj_ae != null && queryConditionObj.customer_id_obj_ae.length == 1) {
                        queryConditionObj.customer_id_obj_ae = queryConditionObj.customer_id_obj_ae[0];
                    }

                    var lidu = queryConditionObj._lidu;
                    if (queryConditionObj.shopType && !queryConditionObj._customerId) {
                        queryConditionObj._customerId = $("#_loginCustomerId").val();
                    }
                    var startDate = queryConditionObj._startDate;
                    var endDate = queryConditionObj._endDate;
                    /*var checkResult = checkDate(startDate,endDate,lidu);
                     if(!checkResult.isSuccess){
                     Dolphin.alert(checkResult.msg);
                     return;
                     }*/
                    if (!(queryConditionObj._customerId
                        || queryConditionObj.shopType
                        || queryConditionObj.customer_id_obj_ae || me._dataList.opts.queryParams._shopIdsStr != "")) {
                        Dolphin.alert(Dolphin.i18n.get("passenger.pleaseChooseOne"));
                        return;
                    }

                    var url = (org.breezee.context.contextPath == '/' ? '' : org.breezee.context.contextPath) + '/api/cadf6a955cdc489ba8dfdcba5757b6e0';
                    var form = $("<form />");
                    form.attr({"style": "display: none", "target": '_blank', "method": "post", "action": url});
                    $('body').append(form);
                    $.each(me._dataList.opts.queryParams, function (key, value) {
                        var input = $("<input>");
                        input.attr({"name": key, "value": value, "type": "hidden"});
                        form.append(input);
                    });
                    form.submit();
                    form.remove();
                }

            });

            //查询
            $(".btn-query").click(function () {
                me.resetChartData();
                var queryConditionObj = Dolphin.form.getValue('.query-form');

                if (queryConditionObj.customer_id_obj_ae != null && queryConditionObj.customer_id_obj_ae.length > 1) {
                    queryConditionObj._shopIds = queryConditionObj.customer_id_obj_ae;
                    queryConditionObj.customer_id_obj_ae = null;
                } else if (queryConditionObj.customer_id_obj_ae != null && queryConditionObj.customer_id_obj_ae.length == 1) {
                    queryConditionObj.customer_id_obj_ae = queryConditionObj.customer_id_obj_ae[0];
                }

                var lidu = queryConditionObj._lidu;
                if (queryConditionObj.shopType && !queryConditionObj._customerId) {
                    queryConditionObj._customerId = $("#_loginCustomerId").val();
                }
                var startDate = queryConditionObj._startDate;
                var endDate = queryConditionObj._endDate;
                /*var checkResult = checkDate(startDate,endDate,lidu);
                     if(!checkResult.isSuccess){
                     Dolphin.alert(checkResult.msg);
                     return;
                 }*/
                if (!(queryConditionObj._customerId
                    || queryConditionObj.shopType
                    || queryConditionObj.customer_id_obj_ae || queryConditionObj._shopIds)) {
                    Dolphin.alert(Dolphin.i18n.get("passenger.pleaseChooseOne"));
                    return;
                }


                if ($('input[name="_radio"]:checked').val() == "shop") {


                    var shopArray = [];

                    var shopCondition = $(".shop_array").val();//查询条件 店铺
                    var shopTypeCondition = $("#shopType").val();//查询条件 店铺类型
                    var shopAreaCondition = $("#customer_select").val();//查询条件 区域

                    if (shopCondition != null && shopCondition.length > 0) {
                        shopArray = $.map(shopCondition, function (n, i) {
                            return {id: n, name: $(".select2-selection__choice")[i].title};
                        });
                    } else if ((shopTypeCondition != null && shopTypeCondition.length > 0)
                        || (shopAreaCondition != null && shopAreaCondition.length > 0)) {
                        Dolphin.ajax({
                            url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                            type: Dolphin.requestMethod.POST,
                            data: Dolphin.json2string({
                                properties: {
                                    "selectCustomerId": (shopAreaCondition == null || shopAreaCondition == '' ? $("#_loginCustomerId").val() : shopAreaCondition),
                                    "selectShopType": shopTypeCondition
                                }
                            }),
                            async: false,
                            loading: true,
                            onSuccess: function (reData) {
                                if (reData.rows) {
                                    shopArray = $.map(reData.rows, function (n) {
                                        return {id: n.id, name: n.name};
                                    });
                                }
                            }
                        });
                    }
                    var queryConditionObj = Dolphin.form.getValue('.query-form');
                    var lidu = queryConditionObj._lidu;
                    var startDate = queryConditionObj._startDate;
                    var endDate = queryConditionObj._endDate;
                    if (queryConditionObj.shopType && !queryConditionObj._customerId) {
                        queryConditionObj._customerId = $("#_loginCustomerId").val();
                    }

                    if (!(queryConditionObj._customerId
                        || queryConditionObj.shopType
                        || queryConditionObj.customer_id_obj_ae)) {
                        Dolphin.alert(Dolphin.i18n.get("passenger.pleaseChooseOne"));
                        return;
                    }


                    // $('body > #loading').show(function(){

                    var shopIdArray = _.map(shopArray, function (obj, index) {
                        return obj.id;
                    });
                    queryConditionObj._shopIds = shopIdArray;
                    Dolphin.ajax({
                        url: '/api/e6040baa72d740b6aac64dfef518860b',
                        type: Dolphin.requestMethod.POST,
                        loading: true,
                        data: Dolphin.json2string({properties: queryConditionObj}),
                        onSuccess: function (reData) {

                            let columns = [{
                                code: 'shopName',
                                title: Dolphin.i18n.get("framework.store"),
                                textAlign: 'center',
                                width: "100px",
                                formatter: function (val) {
                                    return val;

                                }
                            }];
                            let compareDetailRows = [];


                            //以店铺或者设备来分组
                            let lineGroup = _.groupBy(reData.rows, function (obj) {
                                return obj.happenTime;
                            });
                            console.log(reData.rows);


                            let idx = 0;
                            _.each(lineGroup, function (shopArray, key) {

                                let legend = key;

                                if (lidu == '3') {
                                    legend = key.substr(0, 10);
                                } else if (lidu == '4') {
                                    let year = $("#startDate").val().substr(0, 4);
                                    legend = getXDate(year, key) + ' 第' + key + '周';
                                } else if (lidu == '5') {
                                    legend = key.substr(0, 7);
                                } else {
                                    let day = key.substr(0, 10);
                                    let startHour = key.substr(11, 2);
                                    let endHour = parseInt(startHour) + 1;
                                    legend = day + ' ' + startHour + ':00-' + endHour + ':00';
                                }


                                let shopIdx = 'time' + idx;
                                columns.push({
                                    code: shopIdx,
                                    title: legend,
                                    width: "100px"
                                });

                                $.each(shopArray, function (index, obj) {
                                    if (compareDetailRows[index] == undefined) {
                                        compareDetailRows[index] = {shopName: obj.shopName};
                                    }
                                    if (obj.dxin == null || obj.dxin == "") {
                                        compareDetailRows[index][shopIdx] = 0;
                                    } else {
                                        compareDetailRows[index][shopIdx] = obj.dxin;
                                    }

                                });
                                idx++;
                            });

                            //总共有多少个店铺或者设备
                            // var shopCnt = shopIdArray.length;
                            // me.barData(lineGroup,reData,lidu,shopCnt);
                            // me.lineData(lineGroup,lidu);


                            //对比数据明细
                            $("#dataList").empty();
                            me._dataList = new Dolphin.LIST({
                                panel: '#dataList',
                                idField: 'id',
                                columns: columns,
                                multiple: false,
                                rowIndex: true,
                                checkbox: false,
                                pagination: false,
                                data: {rows: compareDetailRows}

                            });


                            //数据汇总
                            //以店铺或者设备来分组
                            let lineGroup2 = _.groupBy(reData.rows, function (obj) {
                                return queryConditionObj._radio == 'shop' ? obj.shopName : obj.device.name;
                            });
                            let tempSortMap = {}; //临时对象，用作存储店铺的客流总数，用于排序 格式：｛店铺名：客流总数｝
                            let notEmptyArray = [];
                            let dataTotalArray = [];
                            _.each(lineGroup2, function (shopArray, key) {
                                let inSum = _.reduce(shopArray, function (memo, obj) {
                                    return memo + obj.dxin;
                                }, 0);
                                let outSum = _.reduce(shopArray, function (memo, obj) {
                                    return memo + obj.dxout;
                                }, 0);
                                if (inSum != 0 && inSum != '0') {
                                    notEmptyArray.push(inSum);
                                }
                                tempSortMap[key] = inSum;

                                let tempDataTotalElement = {};
                                _.extend(tempDataTotalElement, _.first(shopArray));
                                tempDataTotalElement.dxin = inSum;
                                tempDataTotalElement.dxout = outSum;
                                tempDataTotalElement.happenTime = queryConditionObj._startDate + ' ~ ' + queryConditionObj._endDate;
                                dataTotalArray.push(tempDataTotalElement);

                            });
                            let reTotalData = {
                                "total": dataTotalArray.length,
                                "success": true,
                                "msg": "Success",
                                "rows": dataTotalArray
                            };
                            //加载数据
                            me._dataTotalList.loadData(reTotalData);
                            //重置进店总数，出点总数
                            $("#inCnt").html(reData.extProps.inCnt);
                            $("#outCnt").html(reData.extProps.outCnt);


                            //总共有多少个店铺或者设备
                            let shopCnt = Object.keys(lineGroup2).length;
                            me.barData(reData, shopCnt, tempSortMap, lidu, notEmptyArray);
                            me.lineData(lineGroup2, lidu);

                            /*//如果大于6个，用柱状图，否则用曲线图
                            if(shopCnt > 6){
                                $('.showBar').click();
                            }else{
                                $('.showLine').click();
                            }*/
                            $('.showBar').click();


                        }
                    });
                } else {
                    me._dataList.load('', queryConditionObj); //数据明细
                    //数据汇总
                    Dolphin.ajax({
                        url: '/api/e6040baa72d740b6aac64dfef518860b',
                        type: Dolphin.requestMethod.POST,
                        loading: true,
                        data: Dolphin.json2string({properties: queryConditionObj}),
                        onSuccess: function (reData) {

                            //以店铺或者设备来分组
                            var lineGroup = _.groupBy(reData.rows, function (obj) {
                                return queryConditionObj._radio == 'shop' ? obj.shopName : obj.device.name;
                            });
                            var tempSortMap = {}; //临时对象，用作存储店铺的客流总数，用于排序 格式：｛店铺名：客流总数｝
                            var notEmptyArray = [];
                            var dataTotalArray = [];
                            _.each(lineGroup, function (shopArray, key) {
                                var inSum = _.reduce(shopArray, function (memo, obj) {
                                    return memo + obj.dxin;
                                }, 0);
                                var outSum = _.reduce(shopArray, function (memo, obj) {
                                    return memo + obj.dxout;
                                }, 0);
                                if (inSum != 0 && inSum != '0') {
                                    notEmptyArray.push(inSum);
                                }
                                tempSortMap[key] = inSum;

                                var tempDataTotalElement = {};
                                _.extend(tempDataTotalElement, _.first(shopArray));
                                tempDataTotalElement.dxin = inSum;
                                tempDataTotalElement.dxout = outSum;
                                tempDataTotalElement.happenTime = queryConditionObj._startDate + ' ~ ' + queryConditionObj._endDate;
                                dataTotalArray.push(tempDataTotalElement);

                            });
                            var reTotalData = {
                                "total": dataTotalArray.length,
                                "success": true,
                                "msg": "Success",
                                "rows": dataTotalArray
                            };
                            //加载数据
                            me._dataTotalList.loadData(reTotalData);
                            //重置进店总数，出点总数
                            $("#inCnt").html(reData.extProps.inCnt);
                            $("#outCnt").html(reData.extProps.outCnt);


                            //总共有多少个店铺或者设备
                            var shopCnt = Object.keys(lineGroup).length;
                            me.barData(reData, shopCnt, tempSortMap, lidu, notEmptyArray);
                            me.lineData(lineGroup, lidu);

                            /*//如果大于6个，用柱状图，否则用曲线图
                            if(shopCnt > 6){
                                $('.showBar').click();
                            }else{
                                $('.showLine').click();
                            }*/
                            $('.showBar').click();
                        }
                    });
                }


            });

            $("#followedFlag").click(function () {
                var customerSelectVal = $("#customer_select").val();
                if (customerSelectVal != null
                    && customerSelectVal != '') {
                    var _this = $("#shop_select");
                    var queryConditionObj = {"selectCustomerId": customerSelectVal};
                    if ($(this).is(':checked')) {
                        queryConditionObj.followed = "Y";
                    }
                    if ($("shopType").val()) {
                        queryConditionObj.selectShopType = $("shopType").val();


                    }

                    _this.empty();
                    Dolphin.ajax({
                        url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                        type: Dolphin.requestMethod.POST,
                        async: false,
                        data: Dolphin.json2string({properties: queryConditionObj}),
                        onSuccess: function (reData) {
                            _this.append(
                                '<option value="">--' + Dolphin.i18n.get("account.pleaseSelect") + '--</option>');
                            $.each(reData.rows, function (index, obj) {
                                _this.append(
                                    '<option value="' + obj.id + '">'
                                    + obj.name + '</option>');
                            });
                        }
                    });
                }
            });

            $(".btn_lidu").click(function () {
                var shopType = $(".custom-radio:checked").val();
                $(".btn_select").removeClass('btn_select').addClass('btn_unselect');
                $(this).removeClass('btn_unselect').addClass('btn_select');
                var liduVal = $(this).data('type');
                $("#lidu_input").val(liduVal);
                if (liduVal == '3') {
                    $(".lidu_hour").hide();
                    // $(".lidu_day").show();
                    // $(".lidu_week").hide();
                    // $(".lidu_month").hide();
                    $("#btn_pressed_week").click();
                    if ('shop' == shopType) {
                        me._dataList.__columns[4].formatter = function (val) {
                            return val.substr(0, 10);
                        }
                    } else {
                        me._dataList.__columns[6].formatter = function (val) {
                            return val.substr(0, 10);
                        }
                    }

                } else if (liduVal == '4') {
                    $(".lidu_hour").hide();
                    // $(".lidu_day").hide();
                    // $(".lidu_week").show();
                    // $(".lidu_month").hide();
                    $("#btn_pressed_month").click();
                    if ('shop' == shopType) {
                        me._dataList.__columns[4].formatter = function (val) {
                            var year = $("#startDate").val().substr(0, 4);
                            return getXDate(year, val) + ' 第' + val + '周';
                        }
                    } else {
                        me._dataList.__columns[6].formatter = function (val) {
                            var year = $("#startDate").val().substr(0, 4);
                            return getXDate(year, val) + ' 第' + val + '周';
                        }
                    }

                } else if (liduVal == '5') {
                    $(".lidu_hour").hide();
                    // $(".lidu_day").hide();
                    // $(".lidu_week").hide();
                    // $(".lidu_month").show();
                    $("#btn_pressed_year").click();
                    if ('shop' == shopType) {
                        me._dataList.__columns[4].formatter = function (val) {
                            return val.substr(0, 7);
                        }
                    } else {
                        me._dataList.__columns[6].formatter = function (val) {
                            return val.substr(0, 7);
                        }
                    }

                } else {
                    $(".lidu_hour").show();
                    // $(".lidu_day").hide();
                    // $(".lidu_week").hide();
                    // $(".lidu_month").hide();
                    $("#btn_pressed_day").click();
                    if ('shop' == shopType) {
                        me._dataList.__columns[4].formatter = function (val) {
                            var day = val.substr(0, 10);
                            var startHour = val.substr(11, 2);
                            var endHour = parseInt(startHour) + 1
                            return day + ' ' + startHour + ':00-' + endHour + ':00';
                        }
                    } else {
                        me._dataList.__columns[6].formatter = function (val) {
                            var day = val.substr(0, 10);
                            var startHour = val.substr(11, 2);
                            var endHour = parseInt(startHour) + 1
                            return day + ' ' + startHour + ':00-' + endHour + ':00';
                        }
                    }
                }
            });

            $(".btn_daterange").click(function () {
                $(".btn_pressed").removeClass('btn_pressed').addClass('btn_unpressed');
                $(this).removeClass('btn_unpressed').addClass('btn_pressed');
                $("#startDate").val($(this).data('beg'));
                $("#endDate").val($(this).data('end'));
            });

        },

        resetChartData: function () {
            let me = this;
            me.const_vars.bar_chartOption_legend_data = [];
            me.const_vars.bar_chartOption_yAxis_data = [];
            me.const_vars.bar_chartOption_series = [];
            me.const_vars.line_chartOption_legend_data = [];
            me.const_vars.line_chartOption_xAxis_data = [];
            me.const_vars.line_chartOption_series = [];
            me.const_vars.chartDiv = 'showDataDiv';
            me.const_vars.shopCnt = 0;
            me.const_vars.chartWidth = 0;

        },

        barData: function (reData, shopCnt, tempSortMap, lidu, notEmptyArray) {
            let me = this;
            //给原始数据增加total属性
            var newReData = _.map(reData.rows, function (obj, index) {
                obj.total = tempSortMap[obj.shopName];
                return obj;
            });
            var barGroup = _.groupBy(newReData, function (obj) {
                return obj.happenTime;
            });

            var chartOption_legend_data = [];
            var chartOption_yAxis_data = [];
            var chartOption_series = [];

            var idx = 0;
            var maxNum = 1000;
            var minNum = 0;
            _.each(barGroup, function (value, key) {
                if (lidu == '3') {//天
                    chartOption_legend_data[idx] = key.substr(5, 5);
                } else if (lidu == '4') {//周
                    var year = $("#startDate").val().substr(0, 4);
                    chartOption_legend_data[idx] = getXDate(year, key) + ' 第' + key + '周';
                } else if (lidu == '5') {//月
                    chartOption_legend_data[idx] = key.substr(5, 2);
                } else {//小时
                    chartOption_legend_data[idx] = key.substr(11, 2);
                }

                var yArray = [];
                var xArray = [];
                var newValue = _.sortBy(value, function (obj) {
                    return obj.total;
                });
                maxNum = Math.max.apply(null, notEmptyArray);
                minNum = Math.min.apply(null, notEmptyArray);
                $.each(newValue, function (index, obj) {
                    xArray.push(obj.dxin);
                    yArray.push(obj.shopName);
                });
                chartOption_yAxis_data = yArray;
                chartOption_series[idx] = {};
                chartOption_series[idx].name = chartOption_legend_data[idx];
                chartOption_series[idx].type = 'bar';
                chartOption_series[idx].stack = Dolphin.i18n.get("passenger.totalAmount");
                chartOption_series[idx].data = xArray;
                chartOption_series[idx].label = {normal: {show: true, position: 'insideRight'}};
                idx++;

            });

            me.const_vars.bar_chartOption_legend_data = chartOption_legend_data;
            me.const_vars.bar_chartOption_yAxis_data = chartOption_yAxis_data;
            me.const_vars.bar_chartOption_series = chartOption_series;
            me.const_vars.chartDiv = 'showDataDiv';
            me.const_vars.shopCnt = shopCnt;
            me.const_vars.chartWidth = parseInt(30 / (minNum / maxNum));


        },
        lineData: function (lineGroup, lidu) {
            let me = this;
            var chartOption_legend_data = [];
            var chartOption_xAxis_data = [];
            var chartOption_series = [];


            var idx = 0;
            var tempDateLen = 0;
            _.each(lineGroup, function (value, key) {

                chartOption_legend_data[idx] = key;

                var flag = false;
                if (tempDateLen < value.length) {
                    tempDateLen = value.length;
                    flag = true;
                }

                var xArray = [];
                var yArray = [];
                $.each(value, function (index, obj) {
                    if (flag) {
                        if (lidu == '3') {//天
                            xArray.push(obj.happenTime.substr(5, 5));
                        } else if (lidu == '4') {//周
                            var year = $("#startDate").val().substr(0, 4);
                            xArray.push(getXDate(year, obj.happenTime) + ' 第' + obj.happenTime + '周');
                        } else if (lidu == '5') {//月
                            xArray.push(obj.happenTime.substr(5, 2));
                        } else {//小时
                            xArray.push(obj.happenTime.substr(11, 2));
                        }
                    }
                    yArray.push(obj.dxin);
                });

                chartOption_xAxis_data = xArray;
                chartOption_series[idx] = {};
                chartOption_series[idx].name = key;
                chartOption_series[idx].type = 'line';
                //chartOption.series[idx].stack = '总量';
                chartOption_series[idx].data = yArray;
                idx++;

            });
            me.const_vars.line_chartOption_legend_data = chartOption_legend_data;
            me.const_vars.line_chartOption_xAxis_data = chartOption_xAxis_data;
            me.const_vars.line_chartOption_series = chartOption_series;
            me.const_vars.chartDiv = 'showDataDiv';
        },

        dataList: function (panelId) {
            let me = this;
            $(panelId).empty();

            var cols = [];

            if ('shop' == $(".custom-radio:checked").val()) {
                cols = [{
                    code: 'customerName',
                    title: Dolphin.i18n.get("frameworkType.client")
                }, {
                    code: 'shopName',
                    title: Dolphin.i18n.get("framework.store")
                }, {
                    code: 'dxin',
                    title: Dolphin.i18n.get("equipment.entry"),
                    width: '110px',
                    textAlign: 'right'
                }, {
                    code: 'dxout',
                    title: Dolphin.i18n.get("equipment.exit"),
                    width: '110px',
                    textAlign: 'right'
                }, {
                    code: 'happenTime',
                    title: Dolphin.i18n.get("equipment.time"),
                    textAlign: 'center',
                    formatter: function (val) {
                        /*
                         if(val.length==19){
                         return val;
                         }else{
                         val = val+"";
                         return val.substring(0,4)+"-"+val.substring(4,6)+"-"+val.substring(6,8)+" "
                         +val.substring(8,10)+":"+val.substring(10,12)+":"+val.substring(12,14);
                         }*/

                    }
                }];
            } else {
                cols = [{
                    code: 'customerName',
                    title: Dolphin.i18n.get("frameworkType.client")
                }, {
                    code: 'shopName',
                    title: Dolphin.i18n.get("framework.store")
                }, {
                    code: 'fullName',
                    title: Dolphin.i18n.get("framework.equipment"),
                    formatter: function (val) {
                        return val ? val : '--';
                    }
                }, {
                    code: 'position',
                    title: Dolphin.i18n.get("framework.equipmentPosition"),
                    formatter: function (val) {
                        return val ? val : '--';
                    }
                }, {
                    code: 'dxin',
                    title: Dolphin.i18n.get("equipment.entry"),
                    width: '110px',
                    textAlign: 'right'
                }, {
                    code: 'dxout',
                    title: Dolphin.i18n.get("equipment.exit"),
                    width: '110px',
                    textAlign: 'right'
                }, {
                    code: 'happenTime',
                    title: Dolphin.i18n.get("equipment.time"),
                    textAlign: 'center',
                    formatter: function (val) {

                    }
                }];
            }

            return new Dolphin.LIST({
                panel: panelId,
                idField: 'id',
                queryParams: {
                    customerId: org.breezee.context.userData.customerId,
                    _loginTopCustomer: "",
                    _shopIdsStr: ""

                },
                columns: cols,
                multiple: false,
                rowIndex: true,
                checkbox: false,
                data: {rows: [], extProps: {totalin: 0, totalout: 0}},
                ajaxType: Dolphin.requestMethod.POST,
                url: '/api/1d618fadeb6b4f588eebe74f965ec731',
                pagination: true,
                onLoadSuccess: function (resData) {

                    if (resData.extProps != null && resData.extProps.totalin != null) {
                        $("#inCnt").text(resData.extProps.totalin);
                    } else {
                        $("#inCnt").text("0");
                    }
                    if (resData.extProps != null && resData.extProps.totalout != null) {
                        $("#outCnt").text(resData.extProps.totalout);
                    } else {
                        $("#outCnt").text("0");
                    }

                }
            });
        },
        dataTotalList: function (panelId) {

            let me = this;
            $(panelId).empty();

            var cols = [];

            if ('shop' == $(".custom-radio:checked").val()) {
                cols = [{
                    code: 'customerName',
                    title: Dolphin.i18n.get("frameworkType.client")
                }, {
                    code: 'shopName',
                    title: Dolphin.i18n.get("framework.store")
                }, {
                    code: 'dxin',
                    title: Dolphin.i18n.get("equipment.entry"),
                    width: '110px',
                    textAlign: 'right'
                }, {
                    code: 'dxout',
                    title: Dolphin.i18n.get("equipment.exit"),
                    width: '110px',
                    textAlign: 'right'
                }, {
                    code: 'happenTime',
                    title: Dolphin.i18n.get("equipment.time"),
                    textAlign: 'center',
                    formatter: function (val) {
                        /*
                         if(val.length==19){
                         return val;
                         }else{
                         val = val+"";
                         return val.substring(0,4)+"-"+val.substring(4,6)+"-"+val.substring(6,8)+" "
                         +val.substring(8,10)+":"+val.substring(10,12)+":"+val.substring(12,14);
                         }*/

                    }
                }];
            } else {
                cols = [{
                    code: 'customerName',
                    title: Dolphin.i18n.get("frameworkType.client")
                }, {
                    code: 'shopName',
                    title: Dolphin.i18n.get("framework.store")
                }, {
                    code: 'fullName',
                    title: Dolphin.i18n.get("framework.equipment"),
                    formatter: function (val) {
                        return val ? val : '--';
                    }
                }, {
                    code: 'position',
                    title: Dolphin.i18n.get("framework.equipmentPosition"),
                    formatter: function (val) {
                        return val ? val : '--';
                    }
                }, {
                    code: 'dxin',
                    title: Dolphin.i18n.get("equipment.entry"),
                    width: '110px',
                    textAlign: 'right'
                }, {
                    code: 'dxout',
                    title: Dolphin.i18n.get("equipment.exit"),
                    width: '110px',
                    textAlign: 'right'
                }, {
                    code: 'happenTime',
                    title: Dolphin.i18n.get("equipment.time"),
                    textAlign: 'center',
                    formatter: function (val) {

                    }
                }];
            }

            return new Dolphin.LIST({
                panel: panelId,
                idField: 'id',
                queryParams: {
                    customerId: org.breezee.context.userData.customerId,
                    _loginTopCustomer: "",
                    _shopIdsStr: ""
                },
                columns: cols,
                multiple: false,
                rowIndex: true,
                checkbox: false,
                data: {rows: [], extProps: {totalin: 0, totalout: 0}},
                ajaxType: Dolphin.requestMethod.POST,
                pagination: false,
                onLoadSuccess: function (resData) {

                    if (resData.extProps != null && resData.extProps.totalin != null) {
                        $("#inCnt").text(resData.extProps.totalin);
                    } else {
                        $("#inCnt").text("0");
                    }
                    if (resData.extProps != null && resData.extProps.totalout != null) {
                        $("#outCnt").text(resData.extProps.totalout);
                    } else {
                        $("#outCnt").text("0");
                    }

                }
            });
        }
    };
    org.breezee.page.init();


});